package com.leetcode;

import com.leetcode.common.ListNode;

import static com.leetcode.util.LinkedListUtil.createList;
import static com.leetcode.util.LinkedListUtil.printList;

/**
 * 24. 两两交换链表中的节点
 * 迭代
 */
public class Solution24 {

    /**
     * 减少变量及逻辑
     *
     * @param head
     * @return
     */
    public ListNode swapPairs(ListNode head) {
        ListNode dummyHead = new ListNode(-1, head);
        ListNode pre = dummyHead;
        while (pre.next != null && pre.next.next != null) {
            ListNode node1 = pre.next;
            ListNode node2 = pre.next.next;

            node1.next = node2.next;
            node2.next = node1;
            pre.next = node2;

            pre = node1;
        }
        return dummyHead.next;
    }

    public ListNode swapPairs1(ListNode head) {
        ListNode dummyHead = new ListNode(-1, head);
        ListNode pre = dummyHead;
        ListNode node1 = pre.next;
        ListNode node2 = null;
        ListNode next = null;
        while (node1 != null && node1.next != null) {
            node2 = node1.next;
            next = node2.next;

            node1.next = next;
            node2.next = node1;
            pre.next = node2;

            pre = node1;
            node1 = next;
        }
        return dummyHead.next;
    }

    public static void main(String[] args) {
        ListNode head = createList(new int[]{1, 2, 3, 4});
        printList(head);

        ListNode newHead = new Solution24().swapPairs(head);
        printList(newHead);
    }

}
